package com.topisv.tms.web;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.topisv.tms.entity.Area;
import com.topisv.tms.entity.BackupTaskOrdeno;
import com.topisv.tms.entity.Customers;
import com.topisv.tms.entity.EdiGoodsSku;
import com.topisv.tms.entity.EdiOrder;
import com.topisv.tms.entity.EdiOrderItem;
import com.topisv.tms.entity.JSONParam;
import com.topisv.tms.entity.OrdenoSource;
import com.topisv.tms.entity.QueryParamHolder;
import com.topisv.tms.entity.ShopSource;
import com.topisv.tms.service.AreaService;
import com.topisv.tms.service.BackupTaskOrdenoService;
import com.topisv.tms.service.CustomerAreaGroupService;
import com.topisv.tms.service.CustomersService;
import com.topisv.tms.service.EdiGoodsSkuService;
import com.topisv.tms.service.EdiOrderItemService;
import com.topisv.tms.service.EdiOrderService;
import com.topisv.tms.service.ShopSourceService;
import com.topisv.tms.service.account.ShiroDbRealm.ShiroUser;
import com.topisv.tms.service.edi.lead.LeadService;
import com.topisv.tms.utils.TimeUtil;
import com.topisv.tms.utils.date.TopIsvDateUtils;
import com.topisv.tms.utils.enums.StatusEnums;
import com.topisv.tms.web.base.BaseDataTableController;

import net.sf.json.JSONObject;

/**
 * 数据源管理
 * 
 * @author Administrator
 * 
 */
@Controller
@RequestMapping(value = "/ediOrderSource")
public class EdiOrderSourceController extends BaseDataTableController{
	private static final Logger logger = LoggerFactory.getLogger(EdiOrderSourceController.class);
	
	private static final int PAGE_SIZE = 40;
	@Autowired
	private EdiOrderService ediOrderService;
	@Autowired
	private EdiOrderItemService ediOrderItemService;
	@Autowired
	private AreaService areaService;
	@Autowired
	private EdiGoodsSkuService ediGoodsSkuService;
	@Autowired
	private BackupTaskOrdenoService backupTaskOrdenoService;
	@Autowired
	private CustomersService customersService;
	@Autowired
	private ShopSourceService shopSourceService;
	@Autowired
	private CustomerAreaGroupService customerAreaGroupService;
	@Autowired
	private LeadService leadService;
	/**
	 * 订单
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "updateOrdenoItems")
	public void updateOrdenoItems(
			@RequestParam(value = "ordenoItems") String ordenoItems,
			@RequestParam(value = "id") Long id,
			HttpServletResponse response) {
		PrintWriter out = null;
		JSONObject json = null;
		try {
			out = response.getWriter();
			json = new JSONObject();
			EdiOrder ediOrder = ediOrderService.findOne(id);
			if (ediOrder == null) {
				json.put("status", "0");
				json.put("content", "该订单不存在");
				out.print(json.toString());
				return;
			}
			ediOrderItemService.updateItems(ordenoItems);//批量更新
			json.put("status", "1");
			json.put("content", "更新成功");
			out.print(json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			
		}
	}
	

	/**
	 * 订单
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "inertsOrdenoItems")
	public void inertsOrdenoItems(
			@RequestParam(value = "skuString") String skuString,
			@RequestParam(value = "id") Long id,
			HttpServletResponse response) {
		PrintWriter out = null;
		JSONObject json = null;
		try {
			out = response.getWriter();
			json = new JSONObject();
			EdiOrder ediOrder = ediOrderService.findOne(id);
			if (ediOrder == null) {
				json.put("status", "0");
				json.put("content", "该订单不存在");
				out.print(json.toString());
				return;
			}
			String[] skuLists = skuString.split("---paiu---");
			ediOrder.setSkuQty(skuLists.length);
			for (int i = 0; i < skuLists.length; i++) {
				String[] skus = skuLists[i].split("===paiu===");
				EdiGoodsSku ediGoodsSku = ediGoodsSkuService.findByCustomerCodeAndSku(ediOrder.getCustomerCode(), skus[0]);
				if (ediGoodsSku == null) {
					ediGoodsSku = new EdiGoodsSku();
					ediGoodsSku.setStoreCode(skus[1]);
					ediGoodsSku.setSku(skus[0]);
					ediGoodsSku.setCustomerCode(ediOrder.getCustomerCode());
				} else {
					if (skus[1] != null
							&& !skus[1].equals(ediGoodsSku.getStoreCode())) {
						ediGoodsSku.setStoreCode(skus[1]);
					}
				}
				ediGoodsSkuService.save(ediGoodsSku);

				EdiOrderItem ediOrderItem = new EdiOrderItem();
				ediOrderItem.setOrdeno(ediOrder.getOrdeno());
				ediOrderItem.setSku(skus[0]);
				ediOrderItem.setWaybillNo(ediOrder.getWaybillNo());
				ediOrderItem.setCustomerCode(ediOrder.getCustomerCode());
				ediOrderItem.setStoreCode(skus[1]);
				ediOrderItem.setQty(Integer.parseInt(skus[2]));
				ediOrderItemService.save(ediOrderItem);

			}
			ediOrderService.save(ediOrder);
			json.put("status", "1");
			json.put("content", "插入成功");
			out.print(json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			
		}
	}

	/**
	 * 更新订单信息
	 * 
	 * @param id
	 * @param response
	 */
	@RequestMapping(value = "updateOrdeno")
	public void updateOrdeno(@RequestParam(value = "ordeno") String ordeno,
			@RequestParam(value = "addres") String addres,
			@RequestParam(value = "provna") String provna,
			@RequestParam(value = "provco") String provco,
			@RequestParam(value = "cityna") String cityna,
			@RequestParam(value = "cityco") String cityco,
			@RequestParam(value = "distna") String distna,
			@RequestParam(value = "distco") String distco,
			@RequestParam(value = "postco") String postco,
			@RequestParam(value = "bunick") String bunick,
			@RequestParam(value = "recena") String recena,
			@RequestParam(value = "mobile") String mobile,
			@RequestParam(value = "teleph") String teleph,
			@RequestParam(value = "shopna") String shopna,
			@RequestParam(value = "ordenoMessage") String ordenoMessage,
			@RequestParam(value = "waybillNo") String waybillNo,
			@RequestParam(value = "customerOrdeno") String customerOrdeno,
			@RequestParam(value = "id") Long id,
			HttpServletResponse response) {
		PrintWriter out = null;
		JSONObject json = null;
		try {
			out = response.getWriter();
			json = new JSONObject();
			EdiOrder ediOrder = ediOrderService.findOne(id);
			if (ediOrder == null) {
				json.put("status", "-1");
				json.put("content", "该订单信息不存在");
				out.print(json.toString());
				return;
			}
			
		    ediOrder.setGymemo(1+"");
			ediOrder.setOrdeno(ordeno);
			ediOrder.setAddres(addres);
			ediOrder.setProvna(provna);
			ediOrder.setProvco(provco);
			ediOrder.setCityna(cityna);
			ediOrder.setCityco(cityco);
			ediOrder.setDistna(distna);
			ediOrder.setDistco(distco);
			ediOrder.setPostco(postco);
			ediOrder.setBunick(bunick);
			ediOrder.setRecena(recena);
			ediOrder.setMobile(mobile);
			ediOrder.setTeleph(teleph);
			ediOrder.setCustomerOrdeno(customerOrdeno);
			ediOrder.setShopna(shopna);
			ediOrder.setWaybillNo(waybillNo);
			ediOrder.setMessage(ordenoMessage);
			
			this.leadService.getAreaProvoNew(ediOrder);//设置省份
			this.leadService.setAreaGroupCode(ediOrder);//设置网点
			ediOrderService.save(ediOrder);
			json.put("status", "1");
			json.put("content", "更新成功");
			out.print(json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			
		}

	}

	/**
	 * 更新订单商品信息
	 * 
	 * @param id
	 * @param ordeno
	 * @param sku
	 * @param storeCode
	 * @param skuQty
	 * @param skuSiz
	 * @param response
	 */
	@RequestMapping(value = "updateOrdenoItem")
	public void updateOrdenoItem(@RequestParam(value = "id") Long id,
			@RequestParam(value = "ordeno") String ordeno,
			@RequestParam(value = "sku") String sku,
			@RequestParam(value = "storeCode") String storeCode,
			@RequestParam(value = "skuQty") Integer skuQty,
			@RequestParam(value = "skuSiz") String skuSiz,
			HttpServletResponse response) {
		PrintWriter out = null;
		JSONObject json = null;
		try {
			out = response.getWriter();
			json = new JSONObject();
			EdiOrderItem ediOrderItem = ediOrderItemService.findOne(id);
			if (ediOrderItem == null) {
				json.put("status", "-1");
				json.put("content", "该记录信息不存在");
				out.print(json.toString());
				return;
			}
			EdiGoodsSku ediGoodsSku = ediGoodsSkuService.findByCustomerCodeAndSku(ediOrderItem.getCustomerCode(), sku);
			if (ediGoodsSku == null) {
				ediGoodsSku = new EdiGoodsSku();
				ediGoodsSku.setCustomerCode(ediOrderItem.getCustomerCode());
				ediGoodsSku.setSku(sku);
				ediGoodsSku.setStoreCode(storeCode);
				ediGoodsSku.setSiz(skuSiz);
				ediGoodsSkuService.save(ediGoodsSku);
			} else {
				if (ediGoodsSku.getStoreCode() != null
						&& !ediGoodsSku.getStoreCode().equals(storeCode)) {
					ediGoodsSku.setStoreCode(storeCode);
				}
				ediGoodsSkuService.save(ediGoodsSku);
			}
			ediOrderItem.setSku(sku);
			ediOrderItem.setQty(skuQty);
			ediOrderItem.setSiz(skuSiz);
			ediOrderItem.setStoreCode(storeCode);
			ediOrderItem.setOrdeno(ordeno);
			ediOrderItemService.save(ediOrderItem);
			json.put("status", "1");
			json.put("content", "更新成功");
			out.print(json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			
		}

	}
	
	/**
	 * 删除订单
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "regainOrdeno")
	public void regainOrdeno(@RequestParam(value = "id") Long id,
			HttpServletResponse response) {
		PrintWriter out = null;
		JSONObject json = null;
		try {
			out = response.getWriter();
			json = new JSONObject();
			ediOrderService.regainOrdeno(id);
			json.put("status", "1");
			json.put("content", "重新发货成功请重新生成拣货批次");
			out.print(json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			
		}
	}

	/**
	 * 删除订单
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "deleteOrdeno")
	public void deleteOrdeno(@RequestParam(value = "id") Long id,
			HttpServletResponse response) {
		PrintWriter out = null;
		JSONObject json = null;
		try {
			out = response.getWriter();
			json = new JSONObject();
			ediOrderService.delete(id);
			json.put("status", "1");
			json.put("content", "删除成功");
			out.print(json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			
		}
	}

	/**
	 * 删除订单明细记录
	 * 
	 * @param id
	 * @param response
	 */
	@RequestMapping(value = "deleteOrdenoItem")
	public void deleteOrdenoItem(@RequestParam(value = "id") Long id,
			HttpServletResponse response) {
		PrintWriter out = null;
		JSONObject json = null;
		try {
			out = response.getWriter();
			json = new JSONObject();
			ediOrderItemService.delete(id);
			json.put("status", "1");
			json.put("content", "删除成功");
			out.print(json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			
		}
	}

	/**
	 * 获得订单明细记录
	 * 
	 * @param id
	 * @param response
	 */
	@RequestMapping(value = "getAjaxOrderItems")
	public void getAjaxOrderItems(@RequestParam(value = "id") String id,
			HttpServletResponse response) {
		PrintWriter out = null;
		JSONObject json = null;
		EdiOrder eo=null;
		try {
			out = response.getWriter();
			json = new JSONObject();
			eo=ediOrderService.findByOrdeno(id);
			if(eo==null){
				eo=ediOrderService.findOne(Long.parseLong(id));
				if(eo==null){
				   json.put("status", "-1");
				   json.put("content", "该订单不存在");
				   out.print(json.toString());
				   return;
				}
			}
			List<EdiOrderItem>  ediOrderItems = ediOrderItemService.findByCustomerCodeAndOrdeno(eo.getCustomerCode(), eo.getOrdeno());
			if (ediOrderItems.isEmpty()) {
				json.put("status", "-1");
				json.put("content", "该订单明细不存在");
				out.print(json.toString());
				return;
			}
			json.put("status", "1");
			json.put("content", ediOrderItems);
			out.print(json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			
		}

	}


	/**
	 * 检索校验订单
	 * 
	 * @return
	 */
	@RequestMapping(value = "searchCheck")
	public String searchCheck() {
		return "resource/searchCheckList";
	}

	@RequestMapping(value = "searchCheck/{nowDate}")
	public String searchCheck(@PathVariable(value = "nowDate") String nowDate,
			Model model) {
		Date fromDate = null;
		Date endDate = null;
		List<EdiOrder> exceptionOrdenos = new ArrayList<EdiOrder>();
		List<EdiOrder> normalOrdenos = new ArrayList<EdiOrder>();
		List<Customers> customers=null;
		ShiroUser user = getShiroUser();
		try {
			log.info("异常订单检索时间:" + nowDate);
			fromDate = TimeUtil.getDate(nowDate);
			endDate = TopIsvDateUtils.addDays(fromDate, 1);
			customers=customersService.loadCustomerByAuthority(user);
			List<EdiOrder> ediOrders = ediOrderService.findByCrtimeBetween(fromDate, endDate);//找出所有订单
		    getExceptionOrdeno(ediOrders,exceptionOrdenos,normalOrdenos,customers);// 获取没有商品明细的订单
			model.addAttribute("exceptionOrdenos", exceptionOrdenos);//找出疑似订单
			model.addAttribute("normalOrdenos", normalOrdenos);//找出正常订单
			List<EdiOrderItem> ediOrderItems = ediOrderItemService.findByCrtimeBetween(fromDate, endDate);
			//deleteExceptionOrdenoItem(ediOrderItems);//删除多余的订单明细
		} catch (Exception e) {
			log.error("searchCheck/" + nowDate, e);
		}
		return "resource/searchCheckList";
	}

	
	private boolean isCustomers(List<Customers> customers ,String customerCode){
		for(Customers code:customers){
			if(customerCode.equals(code.getCustomerCode())){
				return true;
			}
		}
		return false;
	}

	private void getExceptionOrdeno(List<EdiOrder> ediOrders,
			List<EdiOrder> exceptionOrdenos, List<EdiOrder> normalOrdenos,List<Customers> customers) throws Exception {

		try {
			for (EdiOrder e : ediOrders) {
				e.setAddres(e.getAddres().replace(" ", ""));
				if(!isCustomers(customers,e.getCustomerCode())){
					continue;
				}
				
				if("no".equals(e.getOrderStatus())||"cancel".equals(e.getOrderStatus())){//不处理订单与取消单
					continue;
				}
				if("finish".equals(e.getStatus())){//已经处理的订单
					continue;
				}
				//找出没有订单明细的订单
				List<EdiOrderItem> ediOrderItems = ediOrderItemService.findByCustomerCodeAndOrdeno(e.getCustomerCode(), e.getOrdeno());
				if(ediOrderItems.isEmpty()){
					e.setIsspec(-1);
				}else{
					if (e.getOrderType() == null || "".equals(e.getOrderType())) {
						if (ediOrderItems.size() > 1) {
							e.setOrderType("multiple");
						} else if (ediOrderItems.get(0).getQty() > 1) {
							e.setOrderType("multiple");
						} else {
							e.setOrderType("single");
						}
						if(!"forward".equals(e.getForwardSign())){
							e.setForwardSign(e.getOrderType());
						}
						ediOrderService.save(e);
					}
				}
				// 增加疑似订单
				if (!"1".equals(e.getGymemo())) {
					exceptionOrdenos.add(e);
					continue;
				}
				if (ediOrderItems.isEmpty()) {
					exceptionOrdenos.add(e);
					continue;
				}
				
				normalOrdenos.add(e);
			}
		} catch (Exception e) {
			throw e;
		}
	}

	/*
	 * @Autowired private WorklinkOrderService worklinkOrderService;
	 */

	@RequestMapping(value = "verifyOrder")
	public String verifyOrderOradeno() {
		return "resource/verifyOrderOradeno";
	}

	/*
	 * private static Map<String, String> sortTypes = Maps.newLinkedHashMap();
	 * static { sortTypes.put("auto", "自动"); sortTypes.put("ordeno", "订单号"); }
	 */
	
	@RequestMapping(value = "v2_show")
	public String show(Model model){
		ShiroUser user = getShiroUser();
		try {
			String customerCode = null;
			List<Customers> customers=this.customersService.loadCustomerByAuthority(user);//商家信息
			if(StatusEnums.user_type_customer.getStatus().equals((user.userType))){
				customerCode=user.customerCode;
			}else{
				customerCode=customers.get(0).getCustomerCode();
			}
			List<OrdenoSource> ordenoSource=this.customersService.findOrdenoSource(customerCode);//平台
			String erpType = ordenoSource.get(0).getOrdenoSourceCode();
			List<ShopSource> shopSource=this.shopSourceService.findByCustomerCodeAndOrdenoSourceCode(customerCode, erpType);//店铺
			List<Area> areas = areaService.findProvoce();
			model.addAttribute("ordenoSources", ordenoSource);
			model.addAttribute("shopSources", shopSource);
			model.addAttribute("customers", customers);
			model.addAttribute("areas", areas);
		} catch (Exception e) {
			
		}
		return "resource/resourceList";
	}
	
	@RequestMapping(value = "page")
	public void page(@RequestBody JSONParam[] paramJson,ServletRequest request, ServletResponse response) {
		try {
			ShiroUser user = getShiroUser();
			QueryParamHolder paramHolder = collectParam(paramJson);
			Map<String, Object> searchParams = paramHolder.getSearchParams();
			String customerCode = searchParams.get("LIKE_customerCode") == null ? null : String.valueOf(searchParams.get("LIKE_customerCode"));
			List<Customers> customers = this.customersService.loadCustomerByAuthority(user);// 商家信息
			if (customerCode == null) {
				if (StatusEnums.user_type_customer.getStatus().equals((user.userType))) {
					customerCode = user.customerCode;
				} else {
					customerCode = customers.get(0).getCustomerCode();
				}
				searchParams.put("LIKE_customerCode", customerCode);
			}
			Page<EdiOrder> ediOrdersPage = ediOrderService.getPageEdiOrders(paramHolder);
			response.getWriter().print(bulidJSON(ediOrdersPage));
		} catch (Exception e) {
			
		}
	}

	/**
	 * 获取订单明细
	 * 
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "detailed")
	public void detailed(@RequestParam(value = "id") String id,
			HttpServletResponse response) {
		PrintWriter out = null;
		JSONObject json = null;
		EdiOrder ediOrder = null;
		List<EdiOrderItem> ediOrderItems = null;
		try {
			out = response.getWriter();
			json = new JSONObject();
			ediOrder=ediOrderService.findByOrdeno(id);
			
			if (ediOrder == null) {
				ediOrder = ediOrderService.findOne(Long.parseLong(id));
				if (ediOrder == null) {
				  json.put("status", "-1");
				  json.put("content", "该订单不存在");
				  out.print(json.toString());
				  return;
				}
			}
			
			ediOrderItems = ediOrderItemService.findByCustomerCodeAndOrdeno(ediOrder.getCustomerCode(), ediOrder.getOrdeno());
			for (EdiOrderItem eOI : ediOrderItems) {
				EdiGoodsSku eGS = ediGoodsSkuService.findByCustomerCodeAndSku(ediOrder.getCustomerCode(), eOI.getSku());
				if (eGS == null) {
					continue;
				}
				eOI.setCol(eGS.getCol());
				eOI.setSiz(eGS.getSiz());
				eOI.setNam(eGS.getSkuName());
				eOI.setEdiGoodsSku(eGS);
			}
			ediOrder.setSkulst(ediOrderItems);
			
			BackupTaskOrdeno b=backupTaskOrdenoService.findOrdeno(ediOrder.getCustomerCode(), ediOrder.getOrdeno());

			String batchCode=ediOrder.getBatchCode()==null? (b==null? "该订单未分拣":b.getBatchCode()==null? "该订单不属于任何出库批次":b.getBatchCode()):ediOrder.getBatchCode();
			String backupTaskCode=ediOrder.getBackupTaskCode()==null? (b==null? "该订单未分拣":b.getBackupTaskCode()==null? "该订单不属于任何拣货任务":b.getBackupTaskCode()):ediOrder.getBackupTaskCode();
			String batchTaskCode=ediOrder.getBatchTaskCode()==null? (b==null? "该订单未分拣":b.getBatchTaskCode()==null? "该订单还未分拣批次":b.getBatchTaskCode()):ediOrder.getBatchTaskCode();

			
			ediOrder.setBatchCode(batchCode);
			ediOrder.setBackupTaskCode(backupTaskCode);
			ediOrder.setBatchTaskCode(batchTaskCode);
			json.put("status", "1");
			json.put("content", ediOrder);
			out.print(json.toString());
		} catch (Exception e) {
			json.put("status", "0");
			json.put("content", e.getMessage());
			out.print(json.toString());
			
		}
	}

	@RequestMapping(value = "reuse")
	public void reuse(@RequestParam(value = "id") String id,
			HttpServletResponse response) {
		PrintWriter out = null;
		JSONObject json = null;
		
		try {
			response.setCharacterEncoding("utf-8");
			out = response.getWriter();
			json = new JSONObject();
			
			int err = ediOrderService.reUseEdiOrder(id);
			json.put("status", String.valueOf(err));
			switch (err){
			case 1:
				json.put("msg", "库存满足，此订单可以执行仓库作业流程");
				break;
			case -1:
				json.put("msg", "库存不足");
				break;
			case -2:
				json.put("msg", "非库存不足订单");
				break;
			}
			
			out.print(json.toString());
		} catch (Exception e) {
			e.printStackTrace();
			json.put("status", "0");
			json.put("msg", "服务器异常");
			out.print(json.toString());
			
		}
	}
	/**
	 * 张卫泽  批量重接失效订单
	 * @param customerCode
	 * @param warehouseCode
	 * @param dataRange
	 * @param response
	 */
	@RequestMapping(value = "batchReuse")
	public void batchReuse(@RequestParam(value = "customerCode") String customerCode,
			@RequestParam(value = "warehouseCode") String warehouseCode,
			@RequestParam(value = "dataRange") String dataRange,
			HttpServletResponse response) {
		PrintWriter out = null;
		JSONObject json = null;
		
		try {
			response.setCharacterEncoding("utf-8");
			out = response.getWriter();
			json = new JSONObject();
			String[] dates=dataRange.split("-");
			String err = batchReuseEdiOrder(customerCode,warehouseCode,dates[0].trim(),dates[1].trim());
			json.put("status", "1");
			if(err.equals("-1")){
				json.put("msg", "没有可重新接单");
			}else{
				int countOrder=Integer.valueOf(err.split(";")[0]);
				int failOrder=Integer.valueOf(err.split(";")[1]);
				json.put("msg", "共"+countOrder+"单,成功"+(countOrder-failOrder)+",失败"+failOrder);
			}
			out.print(json.toString());
		} catch (Exception e) {
			e.printStackTrace();
			json.put("status", "0");
			json.put("msg", "服务器异常");
			out.print(json.toString());
		}
	}

	/**
	 * 批量重接失效订单
	 * @param id
	 * @return　true 成功，false 失败
	 * @throws Exception
	 */
	private String batchReuseEdiOrder(String customerCode,String warehouseCode,String dateks,String datejs) throws Exception {
		try {
			log.info("批量重新处理失效订单");
			return GetBatchReuseSucessOrFaile(ediOrderService.findEdiOderByCWDD(customerCode, warehouseCode, dateks, datejs));
		} catch (Exception e) {
			throw e;
		}
		
	}
	/**
	 *  得到批量处理的结果(1、全部成功 2、部分成功 -1、失败)
	 * @param ediOrdersList
	 * @return
	 * @throws Exception 
	 */
	private String GetBatchReuseSucessOrFaile(List<EdiOrder> ediOrdersList) throws Exception {
		log.info("批量重新处理失效订单List:"+ediOrdersList+";ListSize:"+ediOrdersList.size());
		if (null != ediOrdersList && !(ediOrdersList.isEmpty())) {
			  return ediOrdersList.size()+";"+getBatchResult(ediOrdersList);
		} else {
			return "-1";
		}
	}
/**
 *  得到批量处理的结果 flag(0:全部成功 >0部分成功)
 * @param ediOrdersList
 * @return
 * @throws Exception 
 */	
	private int getBatchResult(List<EdiOrder> ediOrdersList) throws Exception {
		int flag=0;
		for (int i = 0; i < ediOrdersList.size(); i++) {
			flag=reuseEdiOrderOne(ediOrdersList.get(i),flag);
		}
		return flag;
	}
	/**
	 * 处理单个的订单
	 * @param ediOrders
	 * @param flag
	 * @return
	 * @throws Exception 
	 */
	private int reuseEdiOrderOne(EdiOrder ediOrders, int flag) throws Exception {
		return ediOrderService.reUseEdiOrder(ediOrders.getId().toString())>=0 ? flag:(++flag);
	}
}
